package cn.itsource.minio.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.itsource.minio.service.IMinioService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class IMinioServiceImpl implements IMinioService {
    @Value("${minio.endpoint}")
    private  String endpoint;
    @Value("${minio.access-key}")
    private String accessKey;
    @Value("${minio.secret-key}")
    private String secretKey;
    //动态得到yml里面的桶名
    @Value("${minio.bucket}")
    private String bucket;

    /**
     * 创建minio客户端
     * @return
     */
    public  MinioClient createMinioClint(){
         return MinioClient.builder()
                 .endpoint(endpoint)//minio服务器地址
                 .credentials(accessKey, secretKey)
                 .build();
    }
    @Override
    public String upload(MultipartFile file) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        //创建客户端
        MinioClient minioClient = createMinioClint();

        //获取文件的真实名字
        String filename = file.getOriginalFilename();
        //随机生成的文件名
        String newFileName = System.currentTimeMillis()+"."+ FileNameUtil.getSuffix(filename);
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .object(newFileName)    //文件名
                .contentType(file.getContentType())    //文件类型
                .bucket(bucket)  //存储目录名
                .stream(file.getInputStream(), file.getSize(), -1)//file.length() 表示文件大小  -1表示不分片上传
                .build();

        //上传代码
        minioClient.putObject(putObjectArgs);
         //返回上传附件的url地址
          String url = endpoint+"/"+bucket+"/"+newFileName;
          return url;

    }

    /**
     * 删除云服务器附件
     */
    @Override
    public void delete(String objectName) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //创建客户端
        MinioClient minioClient = createMinioClint();
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                .bucket(bucket)
                .object(objectName).build();
        minioClient.removeObject(removeObjectArgs);


    }
}
